package com.rafkind.radicaldatagrid 
{
	import flash.geom.Point;
	import mx.core.IBorder;
	import mx.core.UIComponent;
	
	/**
	 * ...
	 * @author Dave Rafkind
	 */
	public class Grid extends UIComponent {
		
		private var model:IModel;
		
		private var upperLeftPixel:Point;
		private var upperLeftCell:Point;
		private var lowerRightCell:Point;
		
		public function Grid() {
			super();
			
			model = new Model();
		}		
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			var columnHeaders:IColumnHeaderModel = model.getColumnHeaders();
			var rowHeaders:IRowHeaderModel = model.getRowHeaders();			
			
			var x:int = 0;
			var y:int = 0;			
			
			var divider:IDivider = rowHeaders.getTopmostDivider();
			y = divider.getHeight();
				
			// top headers
			for (var rowIndex:int = 0; rowIndex < columnHeaders.getRowCount(); rowIndex++) {
				var row:IRowModel = columnHeaders.getRow(rowIndex);
				x = rowHeaders.getTotalWidth();
				for (var columnIndex:int = upperLeftCell.x; x < unscaledWidth && columnIndex < columnHeaders.getColumnCount(); columnIndex++) {
					var header:ICell = row.getCell(columnIndex);
					header.paint(graphics, x, y);
					x += header.getTotalWidth();					
				}				
				y += row.getTotalWidth();				
			}
			
			// left headers
			divider = columnHeaders.getLeftmostDivider();
			x = divider.getThickness();
			
			for (var columnIndex:int = 0; columnIndex < rowHeaders.getColumnCount(); columnIndex++) {
				var column:IColumnModel = rowHeaders.getColumn(columnIndex);
				y = columnHeaders.getTotalHeight();
				for (var rowIndex:int = upperLeftCell.y; y < unscaledHeight && rowHeaders.getRowCount(); rowIndex++) {
					var header:ICell = column.getCell(rowIndex);
					header.paint(graphics, x, y);
					y += header.getTotalHeight();					
				}
				x += column.getTotalWidth();
			}
			
			// cells			
			y = columnHeaders.getTotalHeight();
			for (var rowIndex:int = upperLeftCell.y; y < unscaledHeight && rowIndex < model.getRowCount(); row++) {
				x = rowHeaders.getTotalWidth();
				var row:IRowModel = model.getRow(rowIndex);				
				for (var columnIndex:int = upperLeftCell.x; x < unscaledWidth && columnIndex < model.getColumnCount(); column++) {
					var cell:ICell = row.getCell(columnIndex);
					cell.paint(graphics, x, y);
					x += cell.getTotalWidth();					
				}
				y += row.getTotalHeight();
			}
		}
	}
}